<template>
  <div class="supplier-return-add-page">
    <el-card shadow="never" class="breadcrumb-card">
      <div class="breadcrumb-content">
        <div class="breadcrumb-title">
          <el-icon class="breadcrumb-icon">
            <Box />
          </el-icon>
          <div>
            <p class="breadcrumb-subtitle">仓库管理 · 供应商退货</p>
            <h2 class="breadcrumb-heading">
              {{ isEditMode ? "编辑供应商退货" : "新增供应商退货" }}
            </h2>
          </div>
        </div>
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/SupplierReturnList' }">
            供应商退货
          </el-breadcrumb-item>
          <el-breadcrumb-item>
            {{ isEditMode ? "编辑" : "新增" }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-card>

    <el-card shadow="never" class="form-card">
      <div class="page-header">
        <div class="page-header__content">
          <div class="page-header__title">
            <div class="page-header__icon-wrapper">
              <el-icon class="page-header__icon"><DocumentAdd /></el-icon>
            </div>
            <div class="page-header__text">
              <h2>{{ pageTitle }}</h2>
              <p class="page-header__desc">
                {{
                  isEditMode ? "修改供应商退货单信息" : "创建新的供应商退货单"
                }}
              </p>
            </div>
          </div>
          <el-tag
            :type="isEditMode ? 'warning' : 'success'"
            effect="dark"
            size="large"
            class="page-header__tag"
          >
            <el-icon class="tag-icon"><Box /></el-icon>
            {{ isEditMode ? "编辑模式" : "新增模式" }}
          </el-tag>
        </div>
      </div>

      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="120px"
        class="supplier-return-form"
      >
        <!-- 基础信息 -->
        <div class="form-section">
          <div class="section-header">
            <div class="section-header__main">
              <div class="section-header__icon">
                <el-icon><DocumentAdd /></el-icon>
              </div>
              <div>
                <p class="section-title">基础信息</p>
                <p class="section-subtitle">完善供应商退货单的基础内容</p>
              </div>
            </div>
            <el-tag type="success" effect="light" size="small">
              必填字段
            </el-tag>
          </div>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="退货单编号" prop="returnOrderNo" required>
                <div class="system-code-field">
                  <el-input
                    v-model="formModel.returnOrderNo"
                    placeholder="请输入"
                    clearable
                    class="system-code-input"
                    :disabled="autoGenerateEnabled"
                    @input="handleManualInput"
                  >
                    <template #prefix>
                      <el-icon class="system-code-prefix"><Tickets /></el-icon>
                    </template>
                  </el-input>
                  <div class="system-code-switch-wrapper">
                    <span class="switch-label">系统编号</span>
                    <el-switch
                      v-model="autoGenerateEnabled"
                      :active-text="autoGenerateEnabled ? '开启' : '关闭'"
                      :inactive-text="autoGenerateEnabled ? '开启' : '关闭'"
                      active-color="#4facfe"
                      inactive-color="#dcdfe6"
                      @change="handleAutoGenerateChange"
                      class="system-code-switch"
                    />
                  </div>
                </div>
                <div v-if="autoGenerateEnabled" class="auto-generate-hint">
                  <el-icon class="hint-icon"><InfoFilled /></el-icon>
                  <span>已开启自动生成，每次打开开关将生成新的编码</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="退货单名称" prop="returnOrderName" required>
                <el-input
                  v-model="formModel.returnOrderName"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="退货日期" prop="returnDate" required>
                <el-date-picker
                  v-model="formModel.returnDate"
                  type="date"
                  placeholder="请选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplier" required>
                <div class="supplier-select-field">
                  <el-input
                    v-model="formModel.supplier"
                    placeholder="请选择供应商"
                    readonly
                    clearable
                  />
                  <el-button
                    type="primary"
                    link
                    class="supplier-select-btn"
                    @click="handleOpenSupplierDialog"
                  >
                    <el-icon><Grid /></el-icon>
                    选择
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="采购单号" prop="purchaseOrderNo">
                <div class="purchase-order-select-field">
                  <el-input
                    v-model="formModel.purchaseOrderNo"
                    placeholder="请选择采购单号"
                    clearable
                    readonly
                    style="flex: 1"
                    @clear="handleClearPurchaseOrder"
                  />
                  <el-button
                    type="primary"
                    link
                    class="purchase-order-select-btn"
                    @click="handleOpenPurchaseInboundDialog"
                  >
                    <el-icon><Grid /></el-icon>
                    选择
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购单名称" prop="purchaseOrderName">
                <el-input
                  v-model="formModel.purchaseOrderName"
                  placeholder="自动带出"
                  clearable
                  readonly
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-model="formModel.remarks"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入"
                  maxlength="300"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 退货明细 -->
        <div class="form-section detail-section">
          <div class="section-header">
            <div class="section-header__main">
              <div class="section-header__icon section-header__icon--detail">
                <el-icon><List /></el-icon>
              </div>
              <div>
                <p class="section-title">退货明细</p>
                <p class="section-subtitle">添加供应商退货的明细信息</p>
              </div>
            </div>
            <div class="section-header__actions">
              <el-tag type="info" effect="light" size="small">
                共 {{ formModel.detail.length }} 项
              </el-tag>
              <el-button
                type="primary"
                :icon="Plus"
                size="default"
                @click="handleOpenMaterialSelectDialog"
              >
                添加
              </el-button>
              <el-button
                type="info"
                :icon="Delete"
                size="default"
                @click="handleRemoveSelectedDetails"
                :disabled="selectedDetailRows.length === 0"
              >
                移除
              </el-button>
            </div>
          </div>

          <el-alert
            v-if="detailError"
            type="error"
            show-icon
            :closable="false"
            class="detail-alert"
          >
            {{ detailError }}
          </el-alert>

          <div class="detail-table-wrapper">
            <el-table
              :data="formModel.detail"
              border
              stripe
              class="detail-table"
              @selection-change="handleDetailSelectionChange"
            >
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column
                label="序号"
                width="70"
                align="center"
                type="index"
                :index="(index: number) => index + 1"
              />
              <el-table-column label="物料编号" min-width="140">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.materialNo"
                    placeholder="请选择物料"
                    readonly
                    clearable
                    @clear="handleClearMaterial($index)"
                  >
                    <template #suffix>
                      <el-button
                        type="primary"
                        link
                        size="small"
                        @click="handleOpenMaterialDialog($index)"
                      >
                        <el-icon><Grid /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="物料名称" min-width="140">
                <template #default="{ row }">
                  <el-input
                    v-model="row.materialName"
                    placeholder="自动带出"
                    readonly
                  />
                </template>
              </el-table-column>
              <el-table-column label="规格型号" min-width="120">
                <template #default="{ row }">
                  <el-input
                    v-model="row.specification"
                    placeholder="自动带出"
                    readonly
                  />
                </template>
              </el-table-column>
              <el-table-column label="单位" width="100">
                <template #default="{ row }">
                  <el-input
                    v-model="row.unit"
                    placeholder="自动带出"
                    readonly
                  />
                </template>
              </el-table-column>
              <el-table-column label="批次号" min-width="120">
                <template #default="{ row }">
                  <el-input
                    v-model="row.batchNo"
                    placeholder="请输入"
                    clearable
                  />
                </template>
              </el-table-column>
              <el-table-column label="退货数量" min-width="120" align="center">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.returnQuantity"
                    :min="0"
                    :precision="0"
                    controls-position="right"
                    style="width: 100%"
                    placeholder="请输入"
                  />
                </template>
              </el-table-column>
              <el-table-column label="仓库名称" min-width="200">
                <template #default="{ row, $index }">
                  <div class="warehouse-select-field">
                    <el-input
                      v-model="row.warehouseName"
                      placeholder="请选择仓库"
                      readonly
                      clearable
                      @clear="handleClearWarehouse($index)"
                      style="flex: 1"
                    />
                    <el-button
                      type="primary"
                      link
                      size="small"
                      @click="handleOpenWarehouseDialog($index)"
                      title="选择仓库"
                    >
                      <el-icon><Grid /></el-icon>
                      选择
                    </el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="100"
                align="center"
                fixed="right"
              >
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    link
                    size="small"
                    :icon="Delete"
                    @click="handleRemoveDetail($index)"
                    >移除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="detail-summary">
            <span class="summary-text">
              退货总数:
              <strong class="summary-number">{{ totalReturnQuantity }}</strong>
            </span>
          </div>
        </div>

        <div class="form-actions">
          <el-button @click="handleCancel">关闭</el-button>
          <el-button type="primary" :loading="submitting" @click="handleSubmit"
            >确定</el-button
          >
        </div>
      </el-form>
    </el-card>

    <!-- 供应商选择对话框 -->
    <el-dialog
      v-model="supplierDialogVisible"
      title="选择供应商"
      width="1000px"
      :close-on-click-modal="false"
    >
      <div class="supplier-dialog-search">
        <el-form :inline="true" :model="supplierSearchForm" label-width="auto">
          <el-form-item label="供应商编号/名称">
            <el-input
              v-model="supplierSearchForm.name"
              placeholder="请输入供应商编号/名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleSupplierSearch"
            />
          </el-form-item>
          <el-form-item label="供应商等级">
            <el-select
              v-model="supplierSearchForm.grade"
              placeholder="请选择供应商等级"
              clearable
              filterable
              style="width: 180px"
              :loading="supplierGradeOptionsLoading"
            >
              <el-option
                v-for="item in supplierGradeOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSupplierSearch"
              >查询</el-button
            >
            <el-button @click="handleSupplierReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="supplierTableData"
        v-loading="supplierLoading"
        border
        stripe
        height="400"
        @row-click="handleSupplierRowClick"
        highlight-current-row
      >
        <el-table-column width="60" align="center">
          <template #default="{ row }">
            <el-radio
              v-model="selectedSupplierId"
              :label="row.id"
              @change="() => handleSupplierRowSelect(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="序号" width="70" align="center" type="index">
          <template #default="{ $index }">
            {{
              $index +
              1 +
              (supplierPagination.pageIndex - 1) * supplierPagination.pageSize
            }}
          </template>
        </el-table-column>
        <el-table-column prop="suppnumber" label="供应商编号" min-width="150" />
        <el-table-column prop="suppname" label="供应商名称" min-width="180" />
        <el-table-column prop="suppgrade" label="供应商等级" min-width="140" />
        <el-table-column prop="supppeople" label="联系人" min-width="120" />
        <el-table-column prop="phone" label="联系电话" min-width="150" />
      </el-table>
      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="supplierPagination.pageIndex"
          v-model:page-size="supplierPagination.pageSize"
          :total="supplierPagination.totalCount"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSupplierSizeChange"
          @current-change="handleSupplierCurrentChange"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="supplierDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSupplierConfirm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 物料选择对话框 -->
    <el-dialog
      v-model="materialSelectDialogVisible"
      title="添加物料"
      width="1400px"
      :close-on-click-modal="false"
    >
      <div class="material-select-dialog-search">
        <el-form
          :inline="true"
          :model="materialSelectSearchForm"
          label-width="auto"
        >
          <el-form-item label="物料编号/名称">
            <el-input
              v-model="materialSelectSearchForm.materialName"
              placeholder="请输入物料编号/名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleMaterialSelectSearch"
            />
          </el-form-item>
          <el-form-item label="单位">
            <el-select
              v-model="materialSelectSearchForm.unit"
              placeholder="请选择单位"
              clearable
              filterable
              style="width: 150px"
            >
              <el-option
                v-for="item in unitOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="类型">
            <el-select
              v-model="materialSelectSearchForm.type"
              placeholder="请选择类型"
              clearable
              filterable
              style="width: 150px"
            >
              <el-option
                v-for="item in materialTypeOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库">
            <el-select
              v-model="materialSelectSearchForm.warehouse"
              placeholder="请选择仓库"
              clearable
              filterable
              style="width: 150px"
            >
              <el-option
                v-for="item in materialWarehouseOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="库区">
            <el-select
              v-model="materialSelectSearchForm.reservoir"
              placeholder="请选择库区"
              clearable
              filterable
              style="width: 150px"
            >
              <el-option
                v-for="item in materialReservoirOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="库位">
            <el-select
              v-model="materialSelectSearchForm.seat"
              placeholder="请选择库位"
              clearable
              filterable
              style="width: 150px"
            >
              <el-option
                v-for="item in materialSeatOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleMaterialSelectSearch"
              >查询</el-button
            >
            <el-button @click="handleMaterialSelectReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="materialSelectTableData"
        v-loading="materialSelectLoading"
        border
        stripe
        height="400"
        @selection-change="handleMaterialSelectSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" width="70" align="center" type="index">
          <template #default="{ $index }">
            {{
              $index +
              1 +
              (materialSelectPagination.pageIndex - 1) *
                materialSelectPagination.pageSize
            }}
          </template>
        </el-table-column>
        <el-table-column prop="materialNo" label="物料编号" min-width="120" />
        <el-table-column prop="materialName" label="物料名称" min-width="150" />
        <el-table-column
          prop="specification"
          label="规格型号"
          min-width="120"
        />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="type" label="类型" min-width="120" />
        <el-table-column prop="batchNo" label="批次" min-width="120" />
        <el-table-column label="仓库名称" min-width="150">
          <template #default="{ row }">
            {{ row.warehouseName || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="storageAreaName"
          label="库区名称"
          min-width="120"
        >
          <template #default="{ row }">
            {{ row.storageAreaName || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="storageLocationName"
          label="库位名称"
          min-width="120"
        >
          <template #default="{ row }">
            {{ row.storageLocationName || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="inventory"
          label="库存"
          width="100"
          align="right"
        />
      </el-table>
      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="materialSelectPagination.pageIndex"
          v-model:page-size="materialSelectPagination.pageSize"
          :total="materialSelectPagination.totalCount"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleMaterialSelectSizeChange"
          @current-change="handleMaterialSelectCurrentChange"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleMaterialSelectCancel">取消</el-button>
          <el-button type="primary" @click="handleMaterialSelectConfirm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 仓库选择对话框 -->
    <el-dialog
      v-model="warehouseDialogVisible"
      title="选择仓库"
      width="1000px"
      class="warehouse-dialog"
      :close-on-click-modal="false"
    >
      <div class="warehouse-dialog-summary">
        仓库名称：{{ selectedWarehouseOption?.name || "未选择" }}　 库区名称：{{
          selectedReservoirOption?.name || "未选择"
        }}　 库位名称：{{ selectedSeatOption?.name || "未选择" }}
      </div>
      <div class="warehouse-dialog-columns">
        <div class="warehouse-column">
          <div class="column-title">仓库名称</div>
          <el-input
            v-model="warehouseSearchForm.warehouse"
            placeholder="请输入仓库名称"
            clearable
            @keyup.enter="handleWarehouseSearchSubmit('warehouse')"
            @clear="handleWarehouseSearchSubmit('warehouse')"
          >
            <template #suffix>
              <el-icon
                class="column-search-icon"
                @click.stop="handleWarehouseSearchSubmit('warehouse')"
              >
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-scrollbar class="column-list">
            <div v-loading="warehouseLoading" style="min-height: 200px">
              <div
                v-for="item in warehouseOptions"
                :key="item.id"
                :class="[
                  'column-option',
                  { active: selectedWarehouseId === item.id },
                ]"
                @click="selectWarehouseOption(item)"
              >
                {{ item.name }}
              </div>
              <el-empty
                v-if="!warehouseOptions.length && !warehouseLoading"
                description="暂无数据"
                :image-size="60"
              />
            </div>
          </el-scrollbar>
        </div>
        <div class="warehouse-column">
          <div class="column-title">库区名称</div>
          <el-input
            v-model="warehouseSearchForm.reservoir"
            placeholder="请输入库区名称"
            clearable
            @keyup.enter="handleWarehouseSearchSubmit('reservoir')"
            @clear="handleWarehouseSearchSubmit('reservoir')"
          >
            <template #suffix>
              <el-icon
                class="column-search-icon"
                @click.stop="handleWarehouseSearchSubmit('reservoir')"
              >
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-scrollbar class="column-list">
            <div v-loading="reservoirLoading" style="min-height: 200px">
              <div
                v-for="item in reservoirOptions"
                :key="item.id"
                :class="[
                  'column-option',
                  { active: selectedReservoirId === item.id },
                ]"
                @click="selectReservoirOption(item)"
              >
                {{ item.name }}
              </div>
              <el-empty
                v-if="!reservoirOptions.length && !reservoirLoading"
                description="暂无数据"
                :image-size="60"
              />
            </div>
          </el-scrollbar>
        </div>
        <div class="warehouse-column">
          <div class="column-title">库位名称</div>
          <el-input
            v-model="warehouseSearchForm.seat"
            placeholder="请输入库位名称"
            clearable
            @keyup.enter="handleWarehouseSearchSubmit('seat')"
            @clear="handleWarehouseSearchSubmit('seat')"
          >
            <template #suffix>
              <el-icon
                class="column-search-icon"
                @click.stop="handleWarehouseSearchSubmit('seat')"
              >
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-scrollbar class="column-list">
            <div v-loading="seatLoading" style="min-height: 200px">
              <div
                v-for="item in seatOptions"
                :key="item.id"
                :class="[
                  'column-option',
                  { active: selectedSeatId === item.id },
                ]"
                @click="selectSeatOption(item)"
              >
                {{ item.name }}
              </div>
              <el-empty
                v-if="!seatOptions.length && !seatLoading"
                description="暂无数据"
                :image-size="60"
              />
            </div>
          </el-scrollbar>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="warehouseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleWarehouseConfirm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 采购入库选择对话框 -->
    <el-dialog
      v-model="purchaseInboundDialogVisible"
      title="选择采购入库单"
      width="1200px"
      :close-on-click-modal="false"
    >
      <div class="purchase-inbound-dialog-search">
        <el-form
          :inline="true"
          :model="purchaseInboundSearchForm"
          label-width="auto"
        >
          <el-form-item label="入库单编号/名称">
            <el-input
              v-model="purchaseInboundSearchForm.puchaseCodeName"
              placeholder="请输入入库单编号/名称"
              clearable
              style="width: 200px"
              @keyup.enter="handlePurchaseInboundSearch"
            />
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input
              v-model="purchaseInboundSearchForm.materialName"
              placeholder="请输入物料名称"
              clearable
              style="width: 200px"
              @keyup.enter="handlePurchaseInboundSearch"
            />
          </el-form-item>
          <el-form-item label="入库日期">
            <el-date-picker
              v-model="purchaseInboundSearchForm.inboundDate"
              type="date"
              placeholder="请选择入库日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 180px"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handlePurchaseInboundSearch"
              >查询</el-button
            >
            <el-button @click="handlePurchaseInboundReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="purchaseInboundTableData"
        v-loading="purchaseInboundLoading"
        border
        stripe
        height="400"
        @row-click="handlePurchaseInboundRowClick"
        highlight-current-row
      >
        <el-table-column width="60" align="center">
          <template #default="{ row }">
            <el-radio
              v-model="selectedPurchaseInboundId"
              :label="row.inboundOrderId"
              @change="() => handlePurchaseInboundRowSelect(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="序号" width="70" align="center" type="index">
          <template #default="{ $index }">
            {{
              $index +
              1 +
              (purchaseInboundPagination.pageIndex - 1) *
                purchaseInboundPagination.pageSize
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="inboundOrderNo"
          label="入库单编号"
          min-width="150"
        />
        <el-table-column
          prop="inboundOrderName"
          label="入库单名称"
          min-width="180"
        />
        <el-table-column
          prop="purchaseOrderNo"
          label="采购单号"
          min-width="150"
        />
        <el-table-column
          prop="purchaseOrderName"
          label="采购单名称"
          min-width="180"
        />
        <el-table-column prop="supplierName" label="供应商" min-width="150">
          <template #default="{ row }">
            {{ row.supplierName || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="inboundDate"
          label="入库日期"
          width="120"
          align="center"
        >
          <template #default="{ row }">
            {{
              row.inboundDate
                ? moment(row.inboundDate).format("YYYY-MM-DD")
                : "-"
            }}
          </template>
        </el-table-column>
        <el-table-column prop="materialName" label="物料名称" min-width="150">
          <template #default="{ row }">
            {{ row.materialName || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="inboundQuantity"
          label="入库数量"
          width="100"
          align="right"
        >
          <template #default="{ row }">
            {{ row.inboundQuantity || 0 }}
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="purchaseInboundPagination.pageIndex"
          v-model:page-size="purchaseInboundPagination.pageSize"
          :total="purchaseInboundPagination.totalCount"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePurchaseInboundSizeChange"
          @current-change="handlePurchaseInboundCurrentChange"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="purchaseInboundDialogVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="handlePurchaseInboundConfirm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  ArrowRight,
  Box,
  DocumentAdd,
  List,
  Delete,
  Plus,
  Tickets,
  InfoFilled,
  Grid,
  Search,
} from "@element-plus/icons-vue";
import { computed, nextTick, onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import https from "@/Http/http";
import moment from "moment";
import type { FormInstance, FormRules } from "element-plus";

const router = useRouter();
const route = useRoute();

interface ReturnDetailForm {
  id?: number | null;
  materialNo: string;
  materialName: string;
  specification: string;
  unit: string;
  batchNo: string;
  returnQuantity: number | null;
  warehouseName: string;
  storageAreaName: string;
  storageLocationName?: string;
  principal?: string;
}

const formRef = ref<FormInstance>();
const submitting = ref(false);
const isEditMode = ref(false);
const detailError = ref("");
const autoGenerateEnabled = ref(false);
const isAutoGenerated = ref(false);
const selectedDetailRows = ref<ReturnDetailForm[]>([]);

const formModel = reactive({
  id: null as number | null,
  returnOrderNo: "",
  returnOrderName: "",
  returnDate: moment().format("YYYY-MM-DD"),
  purchaseOrderNo: "",
  purchaseOrderName: "",
  supplier: "",
  remarks: "",
  detail: [] as ReturnDetailForm[],
});

const rules: FormRules = {
  returnOrderNo: [
    { required: true, message: "请输入退货单编号", trigger: "blur" },
  ],
  returnOrderName: [
    { required: true, message: "请输入退货单名称", trigger: "blur" },
  ],
  returnDate: [
    { required: true, message: "请选择退货日期", trigger: "change" },
  ],
  supplier: [{ required: true, message: "请选择供应商", trigger: "change" }],
};

const pageTitle = computed(() =>
  isEditMode.value ? "编辑供应商退货" : "新增供应商退货"
);

const totalReturnQuantity = computed(() => {
  return formModel.detail.reduce((sum, item) => {
    return sum + (item.returnQuantity || 0);
  }, 0);
});

const defaultDetail = (): ReturnDetailForm => ({
  materialNo: "",
  materialName: "",
  specification: "",
  unit: "",
  batchNo: "",
  returnQuantity: null,
  warehouseName: "",
  storageAreaName: "",
  storageLocationName: "",
  principal: "",
});

const generateCode = () => {
  const timestamp = moment().format("YYYYMMDDHHmmss");
  const random = Math.floor(Math.random() * 1000)
    .toString()
    .padStart(3, "0");
  return `SR${timestamp}${random}`;
};

const handleManualInput = () => {
  if (!autoGenerateEnabled.value) {
    isAutoGenerated.value = false;
  }
};

const handleAutoGenerateChange = (value: boolean) => {
  if (value) {
    formModel.returnOrderNo = generateCode();
    isAutoGenerated.value = true;
  } else {
    if (isAutoGenerated.value) {
      formModel.returnOrderNo = "";
      isAutoGenerated.value = false;
    }
  }
};

const handleAddDetail = () => {
  formModel.detail.push(defaultDetail());
  detailError.value = "";
};

const handleOpenMaterialSelectDialog = async () => {
  // 先重置表单和选择
  materialSelectSearchForm.materialName = "";
  materialSelectSearchForm.unit = "";
  materialSelectSearchForm.type = "";
  materialSelectSearchForm.warehouse = "";
  materialSelectSearchForm.reservoir = "";
  materialSelectSearchForm.seat = "";
  materialSelectSelection.value = [];

  // 打开对话框
  materialSelectDialogVisible.value = true;

  // 等待 DOM 更新完成后再加载数据
  await nextTick();
  fetchMaterialSelectOptions();
  fetchMaterialSelectList();
};

const handleRemoveDetail = (index: number) => {
  formModel.detail.splice(index, 1);
  detailError.value = "";
};

const handleDetailSelectionChange = (selection: ReturnDetailForm[]) => {
  selectedDetailRows.value = selection;
};

const handleRemoveSelectedDetails = () => {
  if (selectedDetailRows.value.length === 0) {
    ElMessage.warning("请先选择要移除的明细");
    return;
  }
  selectedDetailRows.value.forEach((row) => {
    const index = formModel.detail.indexOf(row);
    if (index > -1) {
      formModel.detail.splice(index, 1);
    }
  });
  selectedDetailRows.value = [];
  detailError.value = "";
};

const validateDetails = () => {
  if (!formModel.detail.length) {
    detailError.value = "请至少添加一条退货明细";
    return false;
  }
  for (const [idx, item] of formModel.detail.entries()) {
    if (!item.materialNo || !item.materialName) {
      detailError.value = `明细 ${idx + 1} 的物料不能为空`;
      return false;
    }
    if (!item.returnQuantity || item.returnQuantity <= 0) {
      detailError.value = `明细 ${idx + 1} 的退货数量必须大于0`;
      return false;
    }
  }
  detailError.value = "";
  return true;
};

// 供应商选择相关
const supplierDialogVisible = ref(false);
const supplierLoading = ref(false);
const supplierTableData = ref<any[]>([]);
const supplierSearchForm = reactive({
  name: "",
  grade: "",
});
const supplierPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});
const selectedSupplierId = ref<number | null>(null);
const selectedSupplierRow = ref<any | null>(null);
const supplierGradeOptions = ref<string[]>([]);
const supplierGradeOptionsLoading = ref(false);

const handleOpenSupplierDialog = () => {
  supplierDialogVisible.value = true;
  supplierSearchForm.name = "";
  supplierSearchForm.grade = "";
  selectedSupplierId.value = null;
  selectedSupplierRow.value = null;
  fetchSupplierGrades();
  fetchSuppliers();
};

const fetchSupplierGrades = async () => {
  supplierGradeOptionsLoading.value = true;
  try {
    // 先获取所有供应商数据以提取等级选项
    const params: any = {
      pageindex: 1,
      pagesize: 1000,
    };
    const res = await https.Reads.get("/Supplier/ShowSupplier", { params });
    const responseData = res.data || {};
    const code = responseData.code ?? responseData.Code;
    let dataList: any[] = [];

    if (responseData.data !== undefined) {
      dataList = Array.isArray(responseData.data) ? responseData.data : [];
    } else if (responseData.Data !== undefined) {
      dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
    }

    if (code === 1 || code === -1) {
      // 提取所有不重复的供应商等级
      const grades = new Set<string>();
      dataList.forEach((item: any) => {
        if (item.suppgrade) {
          grades.add(item.suppgrade);
        }
      });
      supplierGradeOptions.value = Array.from(grades).sort();
    }
  } catch (error) {
    console.error("获取供应商等级选项失败:", error);
  } finally {
    supplierGradeOptionsLoading.value = false;
  }
};

const fetchSuppliers = async () => {
  supplierLoading.value = true;
  try {
    const params: any = {
      pageindex: supplierPagination.pageIndex,
      pagesize: supplierPagination.pageSize,
    };
    if (supplierSearchForm.name) {
      params.name = supplierSearchForm.name.trim();
    }
    if (supplierSearchForm.grade) {
      params.grade = supplierSearchForm.grade.trim();
    }
    // 只查询启用的供应商
    params.status = 1;

    const res = await https.Reads.get("/Supplier/ShowSupplier", { params });
    const responseData = res.data || {};
    const code = responseData.code ?? responseData.Code;
    let dataList: any[] = [];
    let total = 0;

    if (responseData.data !== undefined) {
      dataList = Array.isArray(responseData.data) ? responseData.data : [];
      total = responseData.totalCount ?? 0;
    } else if (responseData.Data !== undefined) {
      dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
      total = responseData.TotalCount ?? 0;
    }

    if (code === 1 || code === -1) {
      supplierTableData.value = dataList;
      supplierPagination.totalCount = total;
    } else {
      supplierTableData.value = [];
      supplierPagination.totalCount = 0;
    }
  } catch (error) {
    console.error("获取供应商列表失败:", error);
    supplierTableData.value = [];
    supplierPagination.totalCount = 0;
    ElMessage.error("获取供应商列表失败，请稍后重试");
  } finally {
    supplierLoading.value = false;
  }
};

const handleSupplierSearch = () => {
  supplierPagination.pageIndex = 1;
  fetchSuppliers();
};

const handleSupplierReset = () => {
  supplierSearchForm.name = "";
  supplierSearchForm.grade = "";
  supplierPagination.pageIndex = 1;
  fetchSuppliers();
};

const handleSupplierRowClick = (row: any) => {
  selectedSupplierId.value = row.id;
  selectedSupplierRow.value = row;
};

const handleSupplierRowSelect = (row: any) => {
  selectedSupplierRow.value = row;
};

const handleSupplierConfirm = () => {
  if (!selectedSupplierRow.value) {
    ElMessage.warning("请选择供应商");
    return;
  }
  formModel.supplier = selectedSupplierRow.value.suppname || "";
  supplierDialogVisible.value = false;
};

const handleSupplierSizeChange = (size: number) => {
  supplierPagination.pageSize = size;
  supplierPagination.pageIndex = 1;
  fetchSuppliers();
};

const handleSupplierCurrentChange = (page: number) => {
  supplierPagination.pageIndex = page;
  fetchSuppliers();
};

// 采购入库选择相关
const purchaseInboundDialogVisible = ref(false);
const purchaseInboundLoading = ref(false);
const purchaseInboundTableData = ref<any[]>([]);
const purchaseInboundSearchForm = reactive({
  puchaseCodeName: "",
  materialName: "",
  inboundDate: "" as string | null,
});
const purchaseInboundPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});
const selectedPurchaseInboundId = ref<number | null>(null);
const selectedPurchaseInboundRow = ref<any | null>(null);

const handleOpenPurchaseInboundDialog = () => {
  purchaseInboundDialogVisible.value = true;
  purchaseInboundSearchForm.puchaseCodeName = "";
  purchaseInboundSearchForm.materialName = "";
  purchaseInboundSearchForm.inboundDate = null;
  selectedPurchaseInboundId.value = null;
  selectedPurchaseInboundRow.value = null;
  purchaseInboundPagination.pageIndex = 1;
  fetchPurchaseInboundList();
};

const fetchPurchaseInboundList = async () => {
  purchaseInboundLoading.value = true;
  try {
    const params: any = {
      PageIndex: purchaseInboundPagination.pageIndex,
      PageSize: purchaseInboundPagination.pageSize,
    };
    if (purchaseInboundSearchForm.puchaseCodeName) {
      params.PuchaseCodeName = purchaseInboundSearchForm.puchaseCodeName.trim();
    }
    if (purchaseInboundSearchForm.materialName) {
      params.MaterialName = purchaseInboundSearchForm.materialName.trim();
    }
    if (purchaseInboundSearchForm.inboundDate) {
      params.InboundDate = purchaseInboundSearchForm.inboundDate;
    }

    const res = await https.Reads.get("/Warehouse/PurchaseInboundOrder", {
      params,
    });
    const responseData = res.data || {};
    const code = responseData.code ?? responseData.Code;
    let dataList: any[] = [];
    let total = 0;

    if (responseData.data !== undefined) {
      dataList = Array.isArray(responseData.data) ? responseData.data : [];
      total = responseData.totalCount ?? 0;
    } else if (responseData.Data !== undefined) {
      dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
      total = responseData.TotalCount ?? 0;
    }

    if (code === 1 || code === -1) {
      // 去重处理：同一个入库单只保留一条记录（按入库单ID去重）
      const uniqueMap = new Map<number, any>();
      dataList.forEach((item: any) => {
        const inboundOrderId = item.inboundOrderId || item.id;
        if (inboundOrderId && !uniqueMap.has(inboundOrderId)) {
          uniqueMap.set(inboundOrderId, item);
        }
      });
      purchaseInboundTableData.value = Array.from(uniqueMap.values());
      purchaseInboundPagination.totalCount = total;
    } else {
      purchaseInboundTableData.value = [];
      purchaseInboundPagination.totalCount = 0;
    }
  } catch (error) {
    console.error("获取采购入库列表失败:", error);
    purchaseInboundTableData.value = [];
    purchaseInboundPagination.totalCount = 0;
    ElMessage.error("获取采购入库列表失败，请稍后重试");
  } finally {
    purchaseInboundLoading.value = false;
  }
};

const handlePurchaseInboundSearch = () => {
  purchaseInboundPagination.pageIndex = 1;
  fetchPurchaseInboundList();
};

const handlePurchaseInboundReset = () => {
  purchaseInboundSearchForm.puchaseCodeName = "";
  purchaseInboundSearchForm.materialName = "";
  purchaseInboundSearchForm.inboundDate = null;
  purchaseInboundPagination.pageIndex = 1;
  fetchPurchaseInboundList();
};

const handlePurchaseInboundRowClick = (row: any) => {
  selectedPurchaseInboundId.value = row.inboundOrderId || row.id;
  selectedPurchaseInboundRow.value = row;
};

const handlePurchaseInboundRowSelect = (row: any) => {
  selectedPurchaseInboundRow.value = row;
};

const handlePurchaseInboundConfirm = () => {
  if (!selectedPurchaseInboundRow.value) {
    ElMessage.warning("请选择采购入库单");
    return;
  }
  formModel.purchaseOrderNo =
    selectedPurchaseInboundRow.value.purchaseOrderNo || "";
  formModel.purchaseOrderName =
    selectedPurchaseInboundRow.value.purchaseOrderName || "";
  purchaseInboundDialogVisible.value = false;
  ElMessage.success("已选择采购入库单");
};

const handlePurchaseInboundSizeChange = (size: number) => {
  purchaseInboundPagination.pageSize = size;
  purchaseInboundPagination.pageIndex = 1;
  fetchPurchaseInboundList();
};

const handlePurchaseInboundCurrentChange = (page: number) => {
  purchaseInboundPagination.pageIndex = page;
  fetchPurchaseInboundList();
};

const handleClearPurchaseOrder = () => {
  formModel.purchaseOrderNo = "";
  formModel.purchaseOrderName = "";
};

// 物料选择对话框相关（用于添加明细）
const materialSelectDialogVisible = ref(false);
const materialSelectLoading = ref(false);
const materialSelectTableData = ref<any[]>([]);
const materialSelectSearchForm = reactive({
  materialName: "",
  unit: "",
  type: "",
  warehouse: "",
  reservoir: "",
  seat: "",
});
const materialSelectPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});
const materialSelectSelection = ref<any[]>([]);
const unitOptions = ref<string[]>([]);
const materialTypeOptions = ref<string[]>([]);
const materialWarehouseOptions = ref<string[]>([]);
const materialReservoirOptions = ref<string[]>([]);
const materialSeatOptions = ref<string[]>([]);

// 分割仓库名称（格式：仓库/库区/库位）
const splitWarehouseName = (warehouseName?: string) => {
  if (!warehouseName) return { warehouse: "", reservoir: "", seat: "" };
  const parts = warehouseName
    .split("/")
    .map((p) => p.trim())
    .filter(Boolean);
  return {
    warehouse: parts[0] || "",
    reservoir: parts[1] || "",
    seat: parts[2] || "",
  };
};

// 分割仓库名称（格式：仓库 库区 库位，使用空格分割）- 用于物料选择对话框
const splitWarehouseNameBySpace = (warehouseName?: string) => {
  if (!warehouseName) return { warehouse: "", reservoir: "", seat: "" };
  // 使用空格分割，支持多个空格
  const parts = warehouseName
    .split(/\s+/)
    .map((p) => p.trim())
    .filter(Boolean);
  return {
    warehouse: parts[0] || "",
    reservoir: parts[1] || "",
    seat: parts[2] || "",
  };
};

const fetchMaterialSelectList = async () => {
  materialSelectLoading.value = true;
  try {
    const params: any = {
      PageIndex: materialSelectPagination.pageIndex,
      PageSize: materialSelectPagination.pageSize,
    };
    if (materialSelectSearchForm.materialName) {
      params.MaterialName = materialSelectSearchForm.materialName.trim();
    }

    const res = await https.Reads.get("/Warehouse/PurchaseInboundOrder", {
      params,
    });
    const responseData = res.data || {};
    const code = responseData.code ?? responseData.Code;
    let dataList: any[] = [];
    let total = 0;

    if (responseData.data !== undefined) {
      dataList = Array.isArray(responseData.data) ? responseData.data : [];
      total = responseData.totalCount ?? 0;
    } else if (responseData.Data !== undefined) {
      dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
      total = responseData.TotalCount ?? 0;
    }

    if (code === 1 || code === -1) {
      // 处理数据，分割仓库名称并添加筛选字段
      // 注意：仓库名称字段使用空格分割（格式：仓库名称 库区名称 库位名称）
      let processedList = dataList.map((item: any) => {
        const originalWarehouseName = item.warehouseName || "";
        // 使用空格分割仓库名称
        const { warehouse, reservoir, seat } = splitWarehouseNameBySpace(
          originalWarehouseName
        );
        return {
          ...item,
          originalWarehouseName: originalWarehouseName, // 保留原始值
          warehouseName: warehouse, // 仓库名称（分割后的第一部分）
          storageAreaName: reservoir, // 库区名称（分割后的第二部分）
          storageLocationName: seat, // 库位名称（分割后的第三部分）
          type: "生产物料", // 默认类型，实际应该从物料表获取
          inventory: item.inboundQuantity || 0, // 使用入库数量作为库存
        };
      });

      // 前端筛选
      if (materialSelectSearchForm.unit) {
        processedList = processedList.filter(
          (item: any) =>
            (item.unit || "").toLowerCase() ===
            materialSelectSearchForm.unit.toLowerCase()
        );
      }
      if (materialSelectSearchForm.type) {
        processedList = processedList.filter(
          (item: any) =>
            (item.type || "").toLowerCase() ===
            materialSelectSearchForm.type.toLowerCase()
        );
      }
      if (materialSelectSearchForm.warehouse) {
        processedList = processedList.filter((item: any) =>
          (item.warehouseName || "").includes(
            materialSelectSearchForm.warehouse
          )
        );
      }
      if (materialSelectSearchForm.reservoir) {
        processedList = processedList.filter((item: any) =>
          (item.storageAreaName || "").includes(
            materialSelectSearchForm.reservoir
          )
        );
      }
      if (materialSelectSearchForm.seat) {
        processedList = processedList.filter((item: any) =>
          (item.storageLocationName || "").includes(
            materialSelectSearchForm.seat
          )
        );
      }

      materialSelectTableData.value = processedList;
      materialSelectPagination.totalCount = processedList.length;
    } else {
      materialSelectTableData.value = [];
      materialSelectPagination.totalCount = 0;
    }
  } catch (error) {
    console.error("获取物料列表失败:", error);
    materialSelectTableData.value = [];
    materialSelectPagination.totalCount = 0;
    ElMessage.error("获取物料列表失败，请稍后重试");
  } finally {
    materialSelectLoading.value = false;
  }
};

const fetchMaterialSelectOptions = async () => {
  // 获取所有数据以提取选项
  try {
    const params: any = {
      PageIndex: 1,
      PageSize: 1000,
    };
    if (materialSelectSearchForm.materialName) {
      params.MaterialName = materialSelectSearchForm.materialName.trim();
    }

    const res = await https.Reads.get("/Warehouse/PurchaseInboundOrder", {
      params,
    });
    const responseData = res.data || {};
    const code = responseData.code ?? responseData.Code;
    let dataList: any[] = [];

    if (responseData.data !== undefined) {
      dataList = Array.isArray(responseData.data) ? responseData.data : [];
    } else if (responseData.Data !== undefined) {
      dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
    }

    if (code === 1 || code === -1) {
      // 提取不重复的选项
      const units = new Set<string>();
      const types = new Set<string>();
      const warehouses = new Set<string>();
      const reservoirs = new Set<string>();
      const seats = new Set<string>();

      dataList.forEach((item: any) => {
        const originalWarehouseName = item.warehouseName || "";
        // 使用空格分割仓库名称
        const { warehouse, reservoir, seat } = splitWarehouseNameBySpace(
          originalWarehouseName
        );
        if (item.unit) units.add(item.unit);
        if (warehouse) warehouses.add(warehouse);
        if (reservoir) reservoirs.add(reservoir);
        if (seat) seats.add(seat);
        // 类型暂时使用默认值
        types.add("生产物料");
      });

      unitOptions.value = Array.from(units).sort();
      materialTypeOptions.value = Array.from(types).sort();
      materialWarehouseOptions.value = Array.from(warehouses).sort();
      materialReservoirOptions.value = Array.from(reservoirs).sort();
      materialSeatOptions.value = Array.from(seats).sort();
    }
  } catch (error) {
    console.error("获取选项失败:", error);
  }
};

const handleMaterialSelectSearch = () => {
  materialSelectPagination.pageIndex = 1;
  fetchMaterialSelectList();
};

const handleMaterialSelectReset = () => {
  materialSelectSearchForm.materialName = "";
  materialSelectSearchForm.unit = "";
  materialSelectSearchForm.type = "";
  materialSelectSearchForm.warehouse = "";
  materialSelectSearchForm.reservoir = "";
  materialSelectSearchForm.seat = "";
  materialSelectPagination.pageIndex = 1;
  fetchMaterialSelectList();
};

const handleMaterialSelectSelectionChange = (selection: any[]) => {
  materialSelectSelection.value = selection;
};

const handleMaterialSelectConfirm = async () => {
  if (materialSelectSelection.value.length === 0) {
    ElMessage.warning("请至少选择一条物料");
    return;
  }

  const selectedCount = materialSelectSelection.value.length;

  // 将选中的物料添加到明细列表
  materialSelectSelection.value.forEach((item: any) => {
    // 直接使用已经分割好的值（在 fetchMaterialSelectList 中已经处理过）
    // warehouseName 是分割后的仓库名称（第一部分）
    // storageAreaName 是分割后的库区名称（第二部分）
    // storageLocationName 是分割后的库位名称（第三部分）
    const warehouseName = item.warehouseName || "";
    const storageAreaName = item.storageAreaName || "";
    const storageLocationName = item.storageLocationName || "";

    // 组合完整的仓库名称（用于显示，格式：仓库/库区/库位）
    const fullWarehouseName = [
      warehouseName,
      storageAreaName,
      storageLocationName,
    ]
      .filter(Boolean)
      .join("/");

    formModel.detail.push({
      id: null,
      materialNo: item.materialNo || "",
      materialName: item.materialName || "",
      specification: item.specification || "",
      unit: item.unit || "",
      batchNo: item.batchNo || "",
      returnQuantity: null,
      warehouseName: fullWarehouseName,
      storageAreaName: storageAreaName,
      storageLocationName: storageLocationName,
      principal: item.warehousePrincipal || "",
    });
  });

  // 先清空选择，等待 DOM 更新完成后再关闭对话框
  materialSelectSelection.value = [];
  detailError.value = "";

  // 使用 nextTick 确保组件完全卸载后再关闭对话框
  await nextTick();
  materialSelectDialogVisible.value = false;

  ElMessage.success(`已添加 ${selectedCount} 条物料`);
};

const handleMaterialSelectSizeChange = (size: number) => {
  materialSelectPagination.pageSize = size;
  materialSelectPagination.pageIndex = 1;
  fetchMaterialSelectList();
};

const handleMaterialSelectCurrentChange = (page: number) => {
  materialSelectPagination.pageIndex = page;
  fetchMaterialSelectList();
};

const handleMaterialSelectCancel = async () => {
  // 先清空选择，等待 DOM 更新完成后再关闭对话框
  materialSelectSelection.value = [];
  await nextTick();
  materialSelectDialogVisible.value = false;
};

// 保留原有的单个物料选择功能（用于编辑明细中的物料）
const materialDialogVisible = ref(false);
const materialLoading = ref(false);
const materialTableData = ref<any[]>([]);
const materialSearchForm = reactive({
  keyword: "",
});
const materialPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});
const selectedMaterialRow = ref<any | null>(null);
const currentMaterialDetailIndex = ref<number | null>(null);

const handleOpenMaterialDialog = (index: number) => {
  currentMaterialDetailIndex.value = index;
  materialDialogVisible.value = true;
  materialSearchForm.keyword = "";
  selectedMaterialRow.value = null;
  fetchMaterials();
};

const fetchMaterials = async () => {
  materialLoading.value = true;
  try {
    const params: any = {
      PageIndex: materialPagination.pageIndex,
      PageSize: materialPagination.pageSize,
    };
    if (materialSearchForm.keyword) {
      params.MaterialCodeName = materialSearchForm.keyword.trim();
    }
    const res = await https.Reads.get("/MaterialAdd/MaterialGetList", {
      params,
    });
    const responseData = res.data || {};
    const code = responseData.code ?? responseData.Code;
    let dataList: any[] = [];
    let total = 0;

    if (responseData.data !== undefined) {
      dataList = Array.isArray(responseData.data) ? responseData.data : [];
      total = responseData.totalCount ?? 0;
    } else if (responseData.Data !== undefined) {
      dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
      total = responseData.TotalCount ?? 0;
    }

    if (code === 1 || code === -1) {
      materialTableData.value = dataList;
      materialPagination.totalCount = total;
    } else {
      materialTableData.value = [];
      materialPagination.totalCount = 0;
    }
  } catch (error) {
    console.error("获取物料列表失败:", error);
    materialTableData.value = [];
    materialPagination.totalCount = 0;
  } finally {
    materialLoading.value = false;
  }
};

const handleMaterialSearch = () => {
  materialPagination.pageIndex = 1;
  fetchMaterials();
};

const handleMaterialReset = () => {
  materialSearchForm.keyword = "";
  materialPagination.pageIndex = 1;
  fetchMaterials();
};

const handleMaterialRowClick = (row: any) => {
  selectedMaterialRow.value = row;
};

const handleMaterialConfirm = () => {
  if (!selectedMaterialRow.value || currentMaterialDetailIndex.value === null) {
    ElMessage.warning("请选择物料");
    return;
  }
  const detail = formModel.detail[currentMaterialDetailIndex.value];
  if (!detail) {
    ElMessage.error("未找到对应的物料明细");
    return;
  }
  detail.materialNo =
    selectedMaterialRow.value.materialCode ||
    selectedMaterialRow.value.materialcard ||
    "";
  detail.materialName =
    selectedMaterialRow.value.materialName ||
    selectedMaterialRow.value.materialname ||
    "";
  detail.specification =
    selectedMaterialRow.value.specification ||
    selectedMaterialRow.value.materialModelSame ||
    "";
  detail.unit =
    selectedMaterialRow.value.unit ||
    selectedMaterialRow.value.materialUnit ||
    "";
  materialDialogVisible.value = false;
};

const handleClearMaterial = (index: number) => {
  const detail = formModel.detail[index];
  if (!detail) return;
  detail.materialNo = "";
  detail.materialName = "";
  detail.specification = "";
  detail.unit = "";
};

const handleMaterialSizeChange = (size: number) => {
  materialPagination.pageSize = size;
  materialPagination.pageIndex = 1;
  fetchMaterials();
};

const handleMaterialCurrentChange = (page: number) => {
  materialPagination.pageIndex = page;
  fetchMaterials();
};

// 仓库选择相关
const warehouseDialogVisible = ref(false);
const warehouseOptions = ref<any[]>([]);
const reservoirOptions = ref<any[]>([]);
const seatOptions = ref<any[]>([]);
const warehouseSearchForm = reactive({
  warehouse: "",
  reservoir: "",
  seat: "",
});
const selectedWarehouseId = ref<number | null>(null);
const selectedReservoirId = ref<number | null>(null);
const selectedSeatId = ref<number | null>(null);
const selectedWarehouseOption = ref<any | null>(null);
const selectedReservoirOption = ref<any | null>(null);
const selectedSeatOption = ref<any | null>(null);
const currentWarehouseDetailIndex = ref<number | null>(null);
const warehouseLoading = ref(false);
const reservoirLoading = ref(false);
const seatLoading = ref(false);

const normalizeWarehouseOption = (item: any) => ({
  id: item.id ?? item.Id ?? item.warehouseId ?? 0,
  name:
    item.warehousenmae ??
    item.warehouseName ??
    item.Warehousenmae ??
    item.name ??
    "",
});

const normalizeReservoirOption = (item: any) => ({
  id: item.id ?? item.Id ?? item.reservoirId ?? 0,
  name:
    item.reservoirnmae ??
    item.reservoirName ??
    item.Reservoirnmae ??
    item.name ??
    "",
});

const normalizeSeatOption = (item: any) => ({
  id: item.id ?? item.Id ?? item.seatId ?? 0,
  name: item.seatnmae ?? item.seatName ?? item.Seatnmae ?? item.name ?? "",
});

const fetchWarehouseOptions = async () => {
  warehouseLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
    };
    // 如果有搜索关键词，添加搜索参数
    if (warehouseSearchForm.warehouse) {
      params.Warehousenmae = warehouseSearchForm.warehouse.trim();
      params.WarehousenmaeLike = warehouseSearchForm.warehouse.trim();
    }
    const res = await https.Reads.get("/Warehouse/WarehouseList", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    warehouseOptions.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeWarehouseOption(item))
      : [];
  } catch (error) {
    console.error("获取仓库列表失败", error);
    warehouseOptions.value = [];
    ElMessage.error("获取仓库列表失败，请稍后重试");
  } finally {
    warehouseLoading.value = false;
  }
};

const fetchReservoirOptions = async () => {
  reservoirLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
    };
    // 如果有搜索关键词，添加搜索参数
    if (warehouseSearchForm.reservoir) {
      params.Reservoirnmae = warehouseSearchForm.reservoir.trim();
    }
    // 如果选择了仓库，添加仓库ID过滤
    if (selectedWarehouseId.value) {
      params.Warehouseid = selectedWarehouseId.value;
    }
    const res = await https.Reads.get("/Warehouse/ReservoirList", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    reservoirOptions.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeReservoirOption(item))
      : [];
  } catch (error) {
    console.error("获取库区列表失败", error);
    reservoirOptions.value = [];
    ElMessage.error("获取库区列表失败，请稍后重试");
  } finally {
    reservoirLoading.value = false;
  }
};

const fetchSeatOptions = async () => {
  seatLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
    };
    // 如果有搜索关键词，添加搜索参数
    if (warehouseSearchForm.seat) {
      params.Seatnmae = warehouseSearchForm.seat.trim();
    }
    // 如果选择了仓库，添加仓库ID过滤
    if (selectedWarehouseId.value) {
      params.Warehouseid = selectedWarehouseId.value;
    }
    // 如果选择了库区，添加库区ID过滤
    if (selectedReservoirId.value) {
      params.Reservoirid = selectedReservoirId.value;
    }
    const res = await https.Reads.get("/Warehouse/Seatlist", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    seatOptions.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeSeatOption(item))
      : [];
  } catch (error) {
    console.error("获取库位列表失败", error);
    seatOptions.value = [];
    ElMessage.error("获取库位列表失败，请稍后重试");
  } finally {
    seatLoading.value = false;
  }
};

const handleOpenWarehouseDialog = async (detailIndex: number) => {
  currentWarehouseDetailIndex.value = detailIndex;
  warehouseDialogVisible.value = true;

  // 重置选择状态
  selectedWarehouseId.value = null;
  selectedReservoirId.value = null;
  selectedSeatId.value = null;
  selectedWarehouseOption.value = null;
  selectedReservoirOption.value = null;
  selectedSeatOption.value = null;
  warehouseSearchForm.warehouse = "";
  warehouseSearchForm.reservoir = "";
  warehouseSearchForm.seat = "";

  // 先加载仓库选项
  await fetchWarehouseOptions();

  // 获取当前行的仓库信息
  const detail = formModel.detail[detailIndex];
  if (detail && detail.warehouseName) {
    // 解析仓库名称（格式：仓库/库区/库位）
    const parts = detail.warehouseName
      .split("/")
      .map((p: string) => p.trim())
      .filter(Boolean);
    const currentWarehouseName = parts[0] || "";
    const currentReservoirName = detail.storageAreaName || parts[1] || "";
    const currentSeatName = detail.storageLocationName || parts[2] || "";

    // 如果存在仓库名称，尝试查找并预选
    if (currentWarehouseName) {
      const warehouseOption = warehouseOptions.value.find(
        (item) => item.name === currentWarehouseName
      );
      if (warehouseOption) {
        selectedWarehouseId.value = warehouseOption.id;
        selectedWarehouseOption.value = warehouseOption;
        warehouseSearchForm.warehouse = currentWarehouseName;

        // 加载库区选项
        await fetchReservoirOptions();

        // 如果存在库区名称，尝试查找并预选
        if (currentReservoirName) {
          const reservoirOption = reservoirOptions.value.find(
            (item) => item.name === currentReservoirName
          );
          if (reservoirOption) {
            selectedReservoirId.value = reservoirOption.id;
            selectedReservoirOption.value = reservoirOption;
            warehouseSearchForm.reservoir = currentReservoirName;
          }
        }

        // 加载库位选项
        await fetchSeatOptions();

        // 如果存在库位名称，尝试查找并预选
        if (currentSeatName) {
          const seatOption = seatOptions.value.find(
            (item) => item.name === currentSeatName
          );
          if (seatOption) {
            selectedSeatId.value = seatOption.id;
            selectedSeatOption.value = seatOption;
            warehouseSearchForm.seat = currentSeatName;
          }
        }
      } else {
        // 如果找不到仓库，仍然加载库区和库位选项
        await fetchReservoirOptions();
        await fetchSeatOptions();
      }
    } else {
      // 如果没有仓库名称，加载所有选项
      await fetchReservoirOptions();
      await fetchSeatOptions();
    }
  } else {
    // 如果没有仓库信息，加载所有选项
    await fetchReservoirOptions();
    await fetchSeatOptions();
  }
};

const handleWarehouseSearchSubmit = (
  type: "warehouse" | "reservoir" | "seat"
) => {
  if (type === "warehouse") {
    fetchWarehouseOptions();
  } else if (type === "reservoir") {
    fetchReservoirOptions();
  } else {
    fetchSeatOptions();
  }
};

const selectWarehouseOption = (option: any) => {
  selectedWarehouseId.value = option.id;
  selectedWarehouseOption.value = option;
  selectedReservoirId.value = null;
  selectedReservoirOption.value = null;
  selectedSeatId.value = null;
  selectedSeatOption.value = null;
  fetchReservoirOptions();
  fetchSeatOptions();
};

const selectReservoirOption = (option: any) => {
  selectedReservoirId.value = option.id;
  selectedReservoirOption.value = option;
  selectedSeatId.value = null;
  selectedSeatOption.value = null;
  fetchSeatOptions();
};

const selectSeatOption = (option: any) => {
  selectedSeatId.value = option.id;
  selectedSeatOption.value = option;
};

const handleWarehouseConfirm = () => {
  if (currentWarehouseDetailIndex.value === null) {
    ElMessage.warning("请选择仓库");
    return;
  }
  if (!selectedWarehouseOption.value) {
    ElMessage.warning("请选择仓库");
    return;
  }
  const detail = formModel.detail[currentWarehouseDetailIndex.value];
  if (!detail) {
    ElMessage.error("未找到对应的物料明细");
    return;
  }
  const warehouseName = selectedWarehouseOption.value.name || "";
  const reservoirName = selectedReservoirOption.value?.name || "";
  const seatName = selectedSeatOption.value?.name || "";

  detail.warehouseName = [warehouseName, reservoirName, seatName]
    .filter(Boolean)
    .join("/");
  detail.storageAreaName = reservoirName;
  detail.storageLocationName = seatName;
  warehouseDialogVisible.value = false;
};

const handleClearWarehouse = (index: number) => {
  const detail = formModel.detail[index];
  if (!detail) return;
  detail.warehouseName = "";
  detail.storageAreaName = "";
  detail.storageLocationName = "";
};

const buildPayload = () => {
  return {
    id: formModel.id,
    returnOrderNo: formModel.returnOrderNo.trim(),
    returnOrderName: formModel.returnOrderName.trim(),
    returnDate: formModel.returnDate,
    purchaseOrderNo: formModel.purchaseOrderNo?.trim() ?? "",
    purchaseOrderName: formModel.purchaseOrderName?.trim() ?? "",
    supplier: formModel.supplier.trim(),
    remarks: formModel.remarks?.trim() ?? "",
    detail: formModel.detail.map((item) => ({
      returnId: formModel.id || 0,
      materialNo: item.materialNo.trim(),
      materialName: item.materialName.trim(),
      specification: item.specification?.trim() ?? "",
      unit: item.unit?.trim() ?? "",
      batchNo: item.batchNo?.trim() ?? "",
      returnQuantity: item.returnQuantity ?? 0,
      warehouseName: item.warehouseName?.trim() ?? "",
      storageAreaName: item.storageAreaName?.trim() ?? "",
      storageLocationName: item.storageLocationName?.trim() ?? "",
      principal: item.principal?.trim() ?? "",
    })),
  };
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate();
  if (!validateDetails()) {
    ElMessage.error(detailError.value || "请检查退货明细");
    return;
  }
  const payload = buildPayload();
  submitting.value = true;
  const request = isEditMode.value
    ? https.Writes.put("/Warehouse/SupplierReturnUpdate", payload)
    : https.Writes.post("/Warehouse/SupplierReturnAdd", payload);

  request
    .then((res: any) => {
      if ((res.data?.code ?? res.data?.Code) === 1) {
        ElMessage.success(res.data?.msg ?? "操作成功");
        router.push("/SupplierReturnList");
      } else {
        throw new Error(res.data?.msg ?? "操作失败");
      }
    })
    .catch((error: any) => {
      console.error("提交供应商退货失败:", error);
      const msg =
        error?.message ?? error?.response?.data?.msg ?? "提交失败，请稍后重试";
      ElMessage.error(msg);
    })
    .finally(() => {
      submitting.value = false;
    });
};

const handleCancel = () => {
  router.push("/SupplierReturnList");
};

const fetchSupplierReturnDetail = async (id: number) => {
  try {
    // 通过列表接口获取主表数据
    // 注意：列表接口只返回第一条明细，如果需要所有明细，建议后端提供详情接口
    const params: any = {
      PageIndex: 1,
      PageSize: 1000,
    };
    const res = await https.Reads.get("/Warehouse/SupplierReturnList", {
      params,
    });
    const responseData = res.data || {};
    const code = responseData.code ?? responseData.Code;
    let dataList: any[] = [];

    if (responseData.data !== undefined) {
      dataList = Array.isArray(responseData.data) ? responseData.data : [];
    } else if (responseData.Data !== undefined) {
      dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
    }

    const mainData = dataList.find((item: any) => item.id === id);
    if (!mainData) {
      throw new Error("未找到退货单数据");
    }

    // 设置主表数据
    formModel.id = mainData.id;
    formModel.returnOrderNo = mainData.returnOrderNo ?? "";
    formModel.returnOrderName = mainData.returnOrderName ?? "";
    formModel.returnDate = mainData.returnDate || moment().format("YYYY-MM-DD");
    formModel.purchaseOrderNo = mainData.purchaseOrderNo ?? "";
    formModel.purchaseOrderName = mainData.purchaseOrderName ?? "";
    formModel.supplier = mainData.supplier ?? "";
    formModel.remarks = mainData.remarks ?? "";

    // 由于列表接口只返回第一条明细，这里先使用第一条明细
    // TODO: 建议后端提供获取完整明细的接口，或通过其他方式获取所有明细
    if (mainData.materialNo) {
      formModel.detail = [
        {
          id: mainData.returnId ?? null,
          materialNo: mainData.materialNo ?? "",
          materialName: mainData.materialName ?? "",
          specification: mainData.specification ?? "",
          unit: mainData.unit ?? "",
          batchNo: mainData.batchNo ?? "",
          returnQuantity: mainData.returnQuantity ?? null,
          warehouseName: mainData.warehouseName ?? "",
          storageAreaName: mainData.storageAreaName ?? "",
          storageLocationName: mainData.storageLocationName ?? "",
          principal: mainData.principal ?? "",
        },
      ];
    } else {
      formModel.detail = [defaultDetail()];
    }

    ElMessage.warning("列表接口只返回第一条明细，如需编辑所有明细，请手动添加");
  } catch (error) {
    console.error("获取退货单详情失败:", error);
    throw error;
  }
};

const initializeFromRoute = async () => {
  const { editData, id } = route.query;

  if (!editData && !id) {
    // 新增模式：默认开启自动生成
    autoGenerateEnabled.value = true;
    formModel.returnOrderNo = generateCode();
    isAutoGenerated.value = true;
    handleAddDetail();
    return;
  }

  // 编辑模式
  isEditMode.value = true;
  autoGenerateEnabled.value = false;
  isAutoGenerated.value = false;

  try {
    if (id) {
      // 通过ID获取完整数据
      await fetchSupplierReturnDetail(Number(id));
    } else if (editData) {
      // 通过editData解析数据
      const decoded = decodeURIComponent(editData as string);
      const parsed = JSON.parse(decoded);
      formModel.id = parsed.id ?? null;
      formModel.returnOrderNo = parsed.returnOrderNo ?? "";
      formModel.returnOrderName = parsed.returnOrderName ?? "";
      formModel.returnDate = parsed.returnDate || moment().format("YYYY-MM-DD");
      formModel.purchaseOrderNo = parsed.purchaseOrderNo ?? "";
      formModel.purchaseOrderName = parsed.purchaseOrderName ?? "";
      formModel.supplier = parsed.supplier ?? "";
      formModel.remarks = parsed.remarks ?? "";
      formModel.detail =
        Array.isArray(parsed.detail) && parsed.detail.length
          ? parsed.detail.map((item: any) => ({
              id: item.id ?? null,
              materialNo: item.materialNo ?? "",
              materialName: item.materialName ?? "",
              specification: item.specification ?? "",
              unit: item.unit ?? "",
              batchNo: item.batchNo ?? "",
              returnQuantity: item.returnQuantity ?? null,
              warehouseName: item.warehouseName ?? "",
              storageAreaName: item.storageAreaName ?? "",
              storageLocationName: item.storageLocationName ?? "",
              principal: item.principal ?? "",
            }))
          : [defaultDetail()];
    }
  } catch (error) {
    console.error("解析编辑数据失败:", error);
    ElMessage.warning("编辑参数异常，已切换为新增模式");
    isEditMode.value = false;
    formModel.id = null;
    autoGenerateEnabled.value = true;
    formModel.returnOrderNo = generateCode();
    isAutoGenerated.value = true;
    handleAddDetail();
  }
};

onMounted(() => {
  initializeFromRoute();
});
</script>

<style scoped lang="scss">
.supplier-return-add-page {
  padding: 24px;
  background: linear-gradient(135deg, #f0f4f8 0%, #e8f0f6 50%, #f5f9fc 100%);
  min-height: 100vh;
  position: relative;
  overflow-x: hidden;

  // 添加背景装饰
  &::before {
    content: "";
    position: fixed;
    top: -50%;
    right: -20%;
    width: 600px;
    height: 600px;
    background: radial-gradient(
      circle,
      rgba(64, 158, 255, 0.08) 0%,
      transparent 70%
    );
    border-radius: 50%;
    pointer-events: none;
    z-index: 0;
  }

  &::after {
    content: "";
    position: fixed;
    bottom: -30%;
    left: -10%;
    width: 500px;
    height: 500px;
    background: radial-gradient(
      circle,
      rgba(103, 194, 58, 0.06) 0%,
      transparent 70%
    );
    border-radius: 50%;
    pointer-events: none;
    z-index: 0;
  }

  > * {
    position: relative;
    z-index: 1;
  }

  .breadcrumb-card {
    margin-bottom: 24px;
    border-radius: 16px;
    background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06), 0 2px 8px rgba(0, 0, 0, 0.04);
    border: 1px solid rgba(255, 255, 255, 0.8);
    transition: all 0.3s ease;
    overflow: hidden;

    &:hover {
      box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08), 0 4px 12px rgba(0, 0, 0, 0.06);
      transform: translateY(-2px);
    }

    .breadcrumb-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 4px 0;

      .breadcrumb-title {
        display: flex;
        align-items: center;
        gap: 20px;

        .breadcrumb-icon {
          font-size: 36px;
          color: #409eff;
          filter: drop-shadow(0 2px 4px rgba(64, 158, 255, 0.3));
          transition: all 0.3s ease;

          &:hover {
            transform: scale(1.1) rotate(5deg);
          }
        }

        .breadcrumb-subtitle {
          margin: 0;
          font-size: 13px;
          color: #909399;
          font-weight: 500;
          letter-spacing: 0.5px;
        }

        .breadcrumb-heading {
          margin: 6px 0 0 0;
          font-size: 24px;
          font-weight: 700;
          color: #303133;
          background: linear-gradient(135deg, #303133 0%, #606266 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }
      }
    }
  }

  .form-card {
    border-radius: 16px;
    background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06), 0 2px 8px rgba(0, 0, 0, 0.04);
    border: 1px solid rgba(255, 255, 255, 0.8);
    transition: all 0.3s ease;
    overflow: hidden;

    &:hover {
      box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08), 0 4px 12px rgba(0, 0, 0, 0.06);
    }

    .page-header {
      margin-bottom: 28px;
      padding: 24px 28px 24px;
      border-bottom: 2px solid transparent;
      background: linear-gradient(to bottom, #f8fafc 0%, transparent 100%);
      position: relative;

      &::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 2px;
        background: linear-gradient(
          90deg,
          transparent 0%,
          #e4e7ed 20%,
          #e4e7ed 80%,
          transparent 100%
        );
      }

      &__content {
        display: flex;
        justify-content: space-between;
        align-items: center;

        &__title {
          display: flex;
          align-items: center;
          gap: 20px;

          &__icon-wrapper {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 56px;
            height: 56px;
            border-radius: 14px;
            background: linear-gradient(
              135deg,
              #409eff 0%,
              #66b1ff 50%,
              #85c1ff 100%
            );
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3),
              inset 0 1px 0 rgba(255, 255, 255, 0.2);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;

            &::before {
              content: "";
              position: absolute;
              top: -50%;
              left: -50%;
              width: 200%;
              height: 200%;
              background: linear-gradient(
                45deg,
                transparent 30%,
                rgba(255, 255, 255, 0.3) 50%,
                transparent 70%
              );
              transform: rotate(45deg);
              transition: all 0.6s;
            }

            &:hover {
              transform: translateY(-2px) scale(1.05);
              box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4),
                inset 0 1px 0 rgba(255, 255, 255, 0.3);

              &::before {
                left: 100%;
              }
            }

            .page-header__icon {
              font-size: 28px;
              color: #ffffff;
              filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2));
              position: relative;
              z-index: 1;
            }
          }

          &__text {
            h2 {
              margin: 0;
              font-size: 22px;
              font-weight: 700;
              color: #303133;
              letter-spacing: -0.5px;
            }

            .page-header__desc {
              margin: 6px 0 0 0;
              font-size: 14px;
              color: #909399;
              font-weight: 400;
            }
          }
        }

        &__tag {
          padding: 8px 16px;
          border-radius: 20px;
          font-weight: 600;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }

          .tag-icon {
            margin-right: 6px;
            font-size: 16px;
          }
        }
      }
    }

    .supplier-return-form {
      padding: 0 28px 28px;

      .form-section {
        margin-bottom: 36px;
        padding: 28px;
        background: linear-gradient(135deg, #fafbfc 0%, #ffffff 100%);
        border-radius: 12px;
        border: 1px solid #e4e7ed;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;

        &::before {
          content: "";
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          height: 3px;
          background: linear-gradient(
            90deg,
            #409eff 0%,
            #66b1ff 50%,
            #409eff 100%
          );
          background-size: 200% 100%;
          animation: shimmer 3s infinite;
        }

        @keyframes shimmer {
          0% {
            background-position: -200% 0;
          }
          100% {
            background-position: 200% 0;
          }
        }

        &:hover {
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
          transform: translateY(-2px);
        }

        &.detail-section {
          background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
          border-color: #e4e7ed;

          &::before {
            background: linear-gradient(
              90deg,
              #67c23a 0%,
              #85ce61 50%,
              #67c23a 100%
            );
            background-size: 200% 100%;
          }
        }

        .section-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 24px;
          padding-bottom: 18px;
          border-bottom: 2px solid transparent;
          background: linear-gradient(to bottom, transparent 0%, #f0f2f5 100%);
          position: relative;

          &::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(
              90deg,
              transparent 0%,
              #e4e7ed 20%,
              #e4e7ed 80%,
              transparent 100%
            );
          }

          &__main {
            display: flex;
            align-items: center;
            gap: 16px;

            &__icon {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 44px;
              height: 44px;
              border-radius: 10px;
              background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
              color: #ffffff;
              font-size: 22px;
              box-shadow: 0 3px 10px rgba(64, 158, 255, 0.3);
              transition: all 0.3s ease;

              &:hover {
                transform: rotate(5deg) scale(1.1);
                box-shadow: 0 5px 15px rgba(64, 158, 255, 0.4);
              }

              &--detail {
                background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
                box-shadow: 0 3px 10px rgba(103, 194, 58, 0.3);

                &:hover {
                  box-shadow: 0 5px 15px rgba(103, 194, 58, 0.4);
                }
              }
            }

            .section-title {
              margin: 0;
              font-size: 18px;
              font-weight: 700;
              color: #303133;
              letter-spacing: -0.3px;
            }

            .section-subtitle {
              margin: 5px 0 0 0;
              font-size: 13px;
              color: #909399;
              font-weight: 400;
            }
          }

          &__actions {
            display: flex;
            align-items: center;
            gap: 12px;

            .el-button {
              border-radius: 8px;
              font-weight: 500;
              transition: all 0.3s ease;
              box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);

              &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
              }

              &.el-button--primary {
                background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
                border: none;

                &:hover {
                  background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
                }
              }
            }
          }
        }

        // 表单字段美化
        :deep(.el-form-item) {
          margin-bottom: 22px;

          .el-form-item__label {
            font-weight: 600;
            color: #606266;
            font-size: 14px;
          }

          .el-input__wrapper {
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;

            &:hover {
              box-shadow: 0 2px 6px rgba(64, 158, 255, 0.15);
            }

            &.is-focus {
              box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
            }
          }

          .el-textarea__inner {
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;

            &:hover {
              box-shadow: 0 2px 6px rgba(64, 158, 255, 0.15);
            }

            &:focus {
              box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
            }
          }

          .el-date-editor {
            .el-input__wrapper {
              border-radius: 8px;
            }
          }
        }

        .system-code-field {
          display: flex;
          align-items: center;
          gap: 16px;

          .system-code-input {
            flex: 1;
          }

          .system-code-switch-wrapper {
            display: flex;
            align-items: center;
            gap: 10px;
            white-space: nowrap;
            padding: 8px 16px;
            background: #f5f7fa;
            border-radius: 8px;
            border: 1px solid #e4e7ed;

            .switch-label {
              font-size: 14px;
              color: #606266;
              font-weight: 500;
            }

            .el-switch {
              .el-switch__core {
                border-radius: 12px;
              }
            }
          }
        }

        .auto-generate-hint {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-top: 10px;
          padding: 8px 12px;
          background: linear-gradient(135deg, #ecf5ff 0%, #e1f3ff 100%);
          border-radius: 6px;
          border-left: 3px solid #409eff;
          font-size: 12px;
          color: #606266;

          .hint-icon {
            font-size: 16px;
            color: #409eff;
          }
        }

        .supplier-select-field,
        .warehouse-select-field,
        .purchase-order-select-field {
          display: flex;
          align-items: center;
          gap: 10px;

          .supplier-select-btn,
          .warehouse-select-btn,
          .purchase-order-select-btn {
            flex-shrink: 0;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;

            &:hover {
              transform: translateX(2px);
            }
          }

          .el-button {
            white-space: nowrap;
          }
        }

        .detail-alert {
          margin-bottom: 20px;
          border-radius: 8px;
          border-left: 4px solid #f56c6c;
        }

        .detail-table-wrapper {
          margin-bottom: 20px;
          border-radius: 8px;
          overflow: hidden;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

          .detail-table {
            :deep(.el-table__header) {
              th {
                background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
                color: #303133;
                font-weight: 700;
                font-size: 14px;
                border-bottom: 2px solid #e4e7ed;
              }
            }

            :deep(.el-table__body) {
              tr {
                transition: all 0.2s ease;

                &:hover {
                  background: #f5f7fa;
                  transform: scale(1.01);
                }
              }

              td {
                border-bottom: 1px solid #f0f2f5;
              }
            }

            :deep(.el-input__wrapper) {
              border-radius: 6px;
            }
          }
        }

        .detail-summary {
          display: flex;
          justify-content: flex-end;
          padding: 16px 20px;
          background: linear-gradient(135deg, #f5f7fa 0%, #f0f2f5 100%);
          border-radius: 8px;
          border: 1px solid #e4e7ed;
          box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);

          .summary-text {
            font-size: 15px;
            color: #606266;
            font-weight: 500;

            .summary-number {
              color: #409eff;
              font-size: 20px;
              font-weight: 700;
              margin-left: 8px;
              text-shadow: 0 1px 2px rgba(64, 158, 255, 0.2);
            }
          }
        }
      }

      .form-actions {
        display: flex;
        justify-content: flex-end;
        gap: 16px;
        padding-top: 28px;
        border-top: 2px solid transparent;
        background: linear-gradient(to top, #f0f2f5 0%, transparent 100%);
        position: relative;
        margin-top: 8px;

        &::before {
          content: "";
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          height: 2px;
          background: linear-gradient(
            90deg,
            transparent 0%,
            #e4e7ed 20%,
            #e4e7ed 80%,
            transparent 100%
          );
        }

        .el-button {
          min-width: 100px;
          height: 40px;
          border-radius: 8px;
          font-weight: 600;
          font-size: 14px;
          transition: all 0.3s ease;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }

          &.el-button--primary {
            background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
            border: none;

            &:hover {
              background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
            }

            &:active {
              transform: translateY(0);
            }
          }

          &:not(.el-button--primary) {
            background: #ffffff;
            border-color: #dcdfe6;

            &:hover {
              background: #f5f7fa;
              border-color: #c0c4cc;
            }
          }
        }
      }
    }
  }

  .dialog-search {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;

    .el-input {
      flex: 1;
    }
  }

  .supplier-dialog-search,
  .material-select-dialog-search,
  .purchase-inbound-dialog-search {
    margin-bottom: 20px;
    padding: 20px;
    background: linear-gradient(135deg, #f5f7fa 0%, #fafbfc 100%);
    border-radius: 10px;
    border: 1px solid #e4e7ed;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

    :deep(.el-form-item) {
      margin-bottom: 0;
    }

    :deep(.el-button) {
      border-radius: 8px;
      font-weight: 500;
    }
  }

  .dialog-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 12px 0;
  }

  .warehouse-dialog {
    :deep(.el-dialog__header) {
      padding: 20px 24px;
      background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
      border-bottom: 2px solid #e4e7ed;
    }

    :deep(.el-dialog__body) {
      padding: 24px;
    }

    .warehouse-dialog-summary {
      padding: 14px 18px;
      margin-bottom: 20px;
      background: linear-gradient(135deg, #f5f7fa 0%, #fafbfc 100%);
      border-radius: 8px;
      border-left: 4px solid #409eff;
      font-size: 14px;
      color: #606266;
      font-weight: 500;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
    }

    .warehouse-dialog-columns {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
      height: 420px;

      .warehouse-column {
        display: flex;
        flex-direction: column;
        border: 1px solid #e4e7ed;
        border-radius: 10px;
        overflow: hidden;
        background: #ffffff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
          transform: translateY(-2px);
        }

        .column-title {
          padding: 14px 18px;
          background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
          font-weight: 700;
          color: #303133;
          border-bottom: 2px solid #e4e7ed;
          font-size: 14px;
        }

        .el-input {
          margin: 14px;
          width: calc(100% - 28px);
          border-radius: 8px;

          :deep(.el-input__wrapper) {
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
          }
        }

        .column-list {
          flex: 1;
          padding: 0 14px 14px;

          .column-option {
            padding: 12px 14px;
            margin-bottom: 6px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            color: #606266;
            font-weight: 500;
            border: 1px solid transparent;

            &:hover {
              background: linear-gradient(135deg, #f0f2f5 0%, #e8ecf1 100%);
              border-color: #dcdfe6;
              transform: translateX(4px);
            }

            &.active {
              background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
              color: #ffffff;
              border-color: #409eff;
              box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
              transform: translateX(4px);
            }
          }
        }

        .column-search-icon {
          cursor: pointer;
          color: #909399;
          transition: all 0.3s ease;
          padding: 4px;

          &:hover {
            color: #409eff;
            transform: scale(1.2);
          }
        }
      }
    }
  }

  // 对话框通用样式优化
  :deep(.el-dialog) {
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);

    .el-dialog__header {
      padding: 20px 24px;
      background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
      border-bottom: 2px solid #e4e7ed;
      border-radius: 12px 12px 0 0;

      .el-dialog__title {
        font-weight: 700;
        font-size: 18px;
        color: #303133;
      }
    }

    .el-dialog__body {
      padding: 24px;
    }

    .el-dialog__footer {
      padding: 16px 24px;
      background: #fafbfc;
      border-top: 1px solid #e4e7ed;
      border-radius: 0 0 12px 12px;

      .el-button {
        border-radius: 8px;
        font-weight: 500;
        min-width: 80px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
        }
      }
    }
  }

  // 表格优化
  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;

    .el-table__header-wrapper {
      .el-table__header {
        th {
          background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
        }
      }
    }

    .el-table__body-wrapper {
      .el-table__row {
        transition: all 0.2s ease;

        &:hover {
          background: #f5f7fa;
        }
      }
    }
  }

  // 标签优化
  :deep(.el-tag) {
    border-radius: 6px;
    font-weight: 500;
    padding: 4px 12px;
  }

  // 输入框优化
  :deep(.el-input),
  :deep(.el-textarea) {
    .el-input__wrapper,
    .el-textarea__inner {
      transition: all 0.3s ease;
    }
  }
}
</style>
